/**
 * @ClassName WaitingDemo
 * @Description TODO
 * @Author Li
 * @Date 2022/8/8 10:08
 * @ModifyDate 2022/8/8 10:08
 * @Version 1.0
 */
public class WaitingDemo {
    public static Object obj = new Object(); // 锁对象

    public static void main(String[] args) {
        // 演示waiting
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (obj) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "获取到锁对象，调用wait方法，进入waiting状态，释放锁对象！");
                        obj.wait(); // 无限等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "从waiting状态醒来，获取到锁对象，继续执行！");
                }
            }
        }, "线程一").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "开始执行！");
                    Thread.sleep(1000); // 睡眠1秒，让线程一先获取到锁对象
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁对象，执行完毕，调用notify方法，释放锁对象！");
                    obj.notify(); // 唤醒一个含有wait()方法的线程
                }
            }
        }, "线程二").start();
    }
}
